package gray.boolber.vk.web.api.utils;

import gray.boolber.vk.adapter.NewsFeedAdapter.ViewHolder;
import gray.boolber.vk.web.api.items.News;
import gray.boolber.vk.web.api.manager.NewsFeedManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;


public class AsyncImageLoader extends AsyncTask<Object, View, Bitmap> {
	private Bitmap logo;
	private ViewHolder vh;
	private int pos;
	private News item;
	@Override
	protected Bitmap doInBackground(Object... obj) {
		
		String imageUrl=(String)obj[0];
		String imageSaveAs=(String)obj[1];
//		Log.i("BOOLBER", ""+imageUrl);
		vh=(ViewHolder)obj[2];
		pos=(Integer)obj[3];
		item=NewsFeedManager.INSTANCE.items.get(pos);
          try {
        	  URL url = new URL(imageUrl);
			  URLConnection urlConnection;
			
				if((!new File(imageSaveAs).exists())){
					
					urlConnection = url.openConnection();
					urlConnection.connect();
		            logo=BitmapFactory.decodeStream(urlConnection.getInputStream());
		            File fout=new File(imageSaveAs);
		            fout.getParentFile().mkdirs();
		            FileOutputStream fos=new FileOutputStream(fout);
		            if(logo!=null){
		            	logo.compress(CompressFormat.PNG, 100, fos);
		            }
		            fos.flush();
		            fos.close();
				}else{
					logo=BitmapFactory.decodeFile(imageSaveAs);
				}

			
          } catch(OutOfMemoryError e){
        	  
          } catch (MalformedURLException e) { e.printStackTrace();
          } catch (IOException e) { e.printStackTrace(); }
		return logo;
	}
	
	@Override
	protected void onPostExecute(Bitmap result) {
		super.onPostExecute(result);
//		if(vh.position==pos){
//			long t=System.currentTimeMillis();
//			vh.bm.setImageBitmap(result);
//			vh.text.setText(Html.fromHtml(item.getText()));
//			vh.title.setText(NewsFeedManager.INSTANCE.getSourceTitle(item.getSourceId()));
////			Log.i("BOOLBER", ""+(System.currentTimeMillis()-t));
//		}
	}

}
